package org.coco24.pmstudio.util

import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener
import com.badlogic.gdx.utils.Array
import com.kotcrab.vis.ui.building.utilities.Alignment
import com.kotcrab.vis.ui.building.utilities.CellWidget
import com.kotcrab.vis.ui.util.adapter.ArrayListAdapter
import java.math.BigDecimal
import java.math.RoundingMode

object UIUtils
{
    fun setOnChanged(actor: Actor, runnable: Runnable)
    {
        actor.listeners.removeAll {
            it is ChangeListener
        }
        actor.addListener(object : ChangeListener()
        {
            override fun changed(event: ChangeEvent?, actor: Actor?)
            {
                runnable.run()
            }
        })
    }
    fun centeredWidget(actor: Actor): CellWidget<Actor>
    {
        return CellWidget.of(actor).wrap()
    }
    fun leftWidget(actor: Actor): CellWidget<Actor>
    {
        return CellWidget.of(actor).align(Alignment.LEFT).wrap()
    }
    fun <ItemT, ViewT: Actor> updateList(listAdapter: ArrayListAdapter<ItemT, ViewT>, runnable: Runnable = Runnable {  })
    {
        val selected = kotlin.Array(listAdapter.selection.size) { i -> listAdapter.indexOf(listAdapter.selection[i])}
        runnable.run()
        listAdapter.itemsChanged()
        listAdapter.selection.clear()
        selected.forEach {
            for(i in it downTo 0)
            {
                if(i in 0 until listAdapter.size())
                {
                    listAdapter.selectionManager.select(listAdapter[i])
                    break
                }
            }
        }

    }
    fun setVisible(actor: Actor, visible: Boolean)
    {
        if(actor is WidgetGroup)
        {
            actor.children.forEach {
                setVisible(it, visible)
            }
        }
    }
    fun setOnChangeForeach(actor: Actor, runnable: Runnable)
    {
        if (actor is TextButton)
        {
            actor.addListener(object : ChangeListener()
            {
                override fun changed(event: ChangeEvent?, actor: Actor?)
                {
                    runnable.run()
                }

            })
        }
        else
        if(actor is WidgetGroup)
        {
            actor.children.forEach {
                setOnChangeForeach(it, runnable)
            }
        }
    }
    fun dot2Float(f: Float, s: Int): String
    {
        return BigDecimal(f.toDouble()).setScale(s, RoundingMode.HALF_UP).toString()
    }
}